﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib;
using System.Windows.Forms;
namespace TracyGUI.Model
{
    class NotificationManager
    {
        public static event EventHandler<NotificationEventArgs> NotificationArrived;
        static Action _lastCallback = null;
        static string _lastTitle = null;
        const int MAX_QUEUE_LENGTH = 5;
        static Dictionary<string, Queue<string>> _cachedNotifications = new Dictionary<string,Queue<string>>();
        private static object _lockHelper = new object();
        public static void Notify(object sender, string title, string text, ToolTipIcon icon = ToolTipIcon.Info, Action callback = null)
        {
            lock (_lockHelper)
            {
                _lastCallback = callback;
                _lastTitle = title;

                //Use title as the category
                Queue<string> notificationQueue;
                if (_cachedNotifications.ContainsKey(title))
                {
                    notificationQueue = _cachedNotifications[title];
                }
                else
                {
                    notificationQueue = new Queue<string>();
                    _cachedNotifications.Add(title, notificationQueue);
                }
                //Build text for last MAX_QUEUE_LENGTH notifications
                if (!notificationQueue.Contains(text))
                {
                    notificationQueue.Enqueue(text);
                    while (notificationQueue.Count > MAX_QUEUE_LENGTH)
                    {
                        notificationQueue.Dequeue();
                    }
                }

                StringBuilder sb = new StringBuilder();
                foreach (string notification in notificationQueue.Reverse())
                {
                    sb.AppendLine(notification);
                }
                NotificationArrived.InvokeEvent(sender, new NotificationEventArgs(title, sb.ToString(), icon));
            }
        }

        public static void PerformLastCallback()
        {
            if (_lastCallback != null)
            {
                _lastCallback();
                _lastCallback = null;
            }
            DismissNotification();
        }

        public static void DismissNotification()
        {
            //dismiss notification will clear current queue for the displaying title
            if (_lastTitle != null && _cachedNotifications.ContainsKey(_lastTitle))
            {
                _cachedNotifications.Remove(_lastTitle);
            }
        }
    }
}
